package servicios;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import exceptions.DBException;

import DAOs.DBConnector;
import DAOs.UsuarioDAO;

public abstract class AbstractService {
	private UsuarioDAO dao = new UsuarioDAO();
	
	public void execute() {
		SessionFactory sessionFactory = DBConnector.getSessionFactory();
		Session session = null;
		Transaction trans = null;
			
		try {
			session = sessionFactory.openSession();
			trans = session.beginTransaction();
			
			this.dao.getThreadLocal().set(session);

			this.doYourMagic();
					
			session.flush();
			trans.commit();
		} catch(Exception e) {
			if(trans != null) {
				trans.rollback();
			}
			throw new DBException(e);
		} finally {
			if(session != null) {
				session.close();
				this.dao.getThreadLocal().set(null);
			}	
		}
	}
	
	public abstract void doYourMagic();
	
	public UsuarioDAO getDao() {
		return dao;
	}

	public void setDao(UsuarioDAO dao) {
		this.dao = dao;
	}
	
}
